package com.chengv.redismq.config;

import cn.hutool.core.date.DatePattern;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.core.Ordered;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.TimeZone;

/**
 * 自定义 Jackson 配置
 *
 * @author chengv
 */
@AutoConfiguration
public class MyJacksonAutoConfiguration {

    @Bean
    public MyJackson2ObjectMapperBuilderCustomizer myJackson2ObjectMapperBuilderCustomizer() {
        return new MyJackson2ObjectMapperBuilderCustomizer();
    }

    static final class MyJackson2ObjectMapperBuilderCustomizer
            implements Jackson2ObjectMapperBuilderCustomizer, Ordered {

        @Override
        public int getOrder() {
            return 1;
        }

        @Override
        public void customize(Jackson2ObjectMapperBuilder builder) {
            // 系统默认时区
            builder.timeZone(TimeZone.getDefault());
            // 日期类型禁用时间戳输出
            builder.featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
            builder.featuresToDisable(SerializationFeature.WRITE_DURATIONS_AS_TIMESTAMPS);
            // 日期类型格式统一采用 yyyy-MM-dd HH:mm:ss.SSS
            builder.serializerByType(LocalDate.class, new LocalDateSerializer(DatePattern.NORM_DATE_FORMATTER));
            builder.deserializerByType(LocalDate.class, new LocalDateDeserializer(DatePattern.NORM_DATE_FORMATTER));
            builder.serializerByType(LocalDateTime.class,
                    new LocalDateTimeSerializer(DatePattern.NORM_DATETIME_MS_FORMATTER));
            builder.deserializerByType(LocalDateTime.class,
                    new LocalDateTimeDeserializer(DatePattern.NORM_DATETIME_MS_FORMATTER));
        }
    }
}
